package com.ruangong.GitClient.app.GiteeFile;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import com.ruangong.GitClient.GiteeAPI.GiteeFile;
import com.ruangong.GitClient.GiteeAPI.GiteeFileAdapter;
import com.ruangong.GitClient.GiteeAPI.GiteeRepository;
import com.ruangong.GitClient.GiteeAPI.GiteeUser;
import com.ruangong.GitClient.R;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GiteeFileViewerActivity extends AppCompatActivity {
    private ListView listView;
    private GiteeFileAdapter adapter;
    private List<GiteeFile> fileList;
    //    private static OkHttpClient client = new OkHttpClient();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_giteefile_viewer);

        listView = findViewById(R.id.giteelistView);
        fileList = new ArrayList<>();
        adapter = new GiteeFileAdapter(this, fileList);
        listView.setAdapter(adapter);


        GiteeRepository selectedRepo = getIntent().getParcelableExtra("selectedRepo");

        if (selectedRepo != null) {
            // 如果 selectedRepo 不为空，则执行相应的操作
        } else {
            // 如果 selectedRepo 为空，可以进行相应的错误处理或提示用户
            Log.e("GiteeFileViewerActivity", "selectedRepo is null");
        }

        FetchFilesTask fetchFilesTask = new FetchFilesTask(selectedRepo);
        fetchFilesTask.execute();


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GiteeFile selectedFile = fileList.get(position);
                if (selectedFile.getType().equals("file")) {
                    // 如果是文件，显示文件内容
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // 在新线程中执行网络请求
                            selectedFile.showFileContents(GiteeFileViewerActivity.this);
                        }
                    }).start();
                } else if (selectedFile.getType().equals("dir")) {
                    // 如果是文件夹，递归显示文件夹内容
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                // 在新线程中执行文件夹内容显示操作
                                final List<GiteeFile> directoryContents = selectedFile.showDirAllFiles();

                                if (directoryContents != null) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // 更新ListView的适配器以显示目录内容
                                            fileList.clear();
                                            fileList.addAll(directoryContents);
                                            adapter.notifyDataSetChanged();
                                        }
                                    });
                                } else {
                                    Log.e("GiteeFileViewerActivity", "Directory contents is null");
                                }
                            } catch (Exception e) {
                                Log.e("GiteeFileViewerActivity", "Error in fetching directory contents: " + e.getMessage());
                                e.printStackTrace();
                                // 在这里可以选择如何处理异常，比如弹出错误提示、记录日志等
                            }
                        }
                    }).start();
                }
            }
        });
    }

    private class FetchFilesTask extends AsyncTask<Void, Void, List<GiteeFile>> {

        private GiteeRepository selectedRepo;

        public FetchFilesTask(GiteeRepository selectedRepo) {
            this.selectedRepo = selectedRepo;
        }
        @Override
        protected List<GiteeFile> doInBackground(Void... voids) {
            List<GiteeFile> fileList = new ArrayList<>();
            try {

                String url = selectedRepo.getUrl();
                url = url+ "?access_token=" + GiteeUser.getAccessToken();

                try (Response response = GiteeUser.client.newCall(new Request.Builder().url(url).build()).execute()) {
                    if (response.isSuccessful()) {
                        assert response.body() != null;
                        String responseBody = response.body().string();
                        GiteeRepository giteeRepository = GiteeRepository.fromJson(responseBody);
                        fileList = giteeRepository.getFiles();
                    } else {
                        Log.e("FetchFilesTask", "Failed to fetch repository contents: " + response.message());
                    }
                } catch (IOException e) {
                    Log.e("FetchFilesTask", "Error making HTTP request", e);
                }
            } catch (Exception e) {
                Log.e("FetchFilesTask", "Error processing task", e);
            }

            // 返回文件列表
            return fileList;
        }

        @Override
        protected void onPostExecute(List<GiteeFile> result) {
            super.onPostExecute(result);
            // 在这里更新 UI，假设 adapter 和 fileList 已经定义并初始化
            adapter.clear();
            fileList.addAll(result);
            adapter.notifyDataSetChanged();
        }
    }

}
